<template>
  <view id="appointmentTime" class="page">
    <view class="view_parent">
      <text class="date_text">选择日期 {{ currentSelectedMouth }}月</text>
      <text class="appointable_tip"
        >您可预约{{ appointAheadDays }}天内时间</text
      >
      <view class="border"></view>
      <view class="date_view_parent">
        <view v-for="(item, index) in dateList" v-bind:key="index">
          <view class="selected_date_view_parent" v-if="item.isChecked">
            <view @tap="selectDate(index)" class="selected_date_view"
              ><text class="selected_date_text"
                >{{ item.day }}日({{ item.weekday }})</text
              ></view
            >
          </view>
          <view v-else class="selected_date_view_parent">
            <view @tap="selectDate(index)" class="unselect_date_view"
              ><text class="unselect_date_text"
                >{{ item.day }}日({{ item.weekday }})</text
              ></view
            >
          </view>
        </view>
      </view>
    </view>

    <view class="view_parent_2">
      <text class="select_time_slot_text">选择时间</text>
      <view class="border_select_time_slot"></view>
      <view class="time_view_parent">
        <view v-for="(item, index) in currentTimeSlotsList" v-bind:key="index">
          <view v-if="item.isChecked" class="selected_time_view_parent">
            <view @tap="selectTimeSlot(index)" class="selected_time_view"
              ><text class="selected_time_text_line1"
                >{{ item.startTime }}-{{ item.endTime }}</text
              ><text class="selected_time_text_line2"
                >余{{ item.surplus }}</text
              ></view
            >
          </view>
          <view v-else-if="item.isDisable" class="selected_time_view_parent">
            <view class="disable_time_view" @tap="selectTimeSlot(index)"
              ><text class="disable_time_text_line1"
                >{{ item.startTime }}-{{ item.endTime }}</text
              ><text class="disable_time_text_line2">{{ item.tip }}</text></view
            >
          </view>
          <view v-else class="selected_time_view_parent">
            <view @tap="selectTimeSlot(index)" class="unselect_time_view"
              ><text class="unselect_time_text_line1"
                >{{ item.startTime }}-{{ item.endTime }}</text
              ><text class="unselect_time_text_line2"
                >余{{ item.surplus }}</text
              ></view
            >
          </view>
        </view>
      </view>
    </view>

    <view class="confirm_select_time" @tap="confirm"> 确定 </view>
  </view>
</template>
<script>
import Taro, { getCurrentPages } from "@tarojs/taro";
import "./appointmentTime.less";
import bulterApi from "@souche2014/bulter-api";
const api = bulterApi({ partner: "IOParking" });
export default {
  name: "appointmentTime",
  data() {
    return {
      apiBaseUrl: process.env.IOParking.API_HOST,
      apiMobileUrl: process.env.IOParking.API_CARCODE,
      dateList: [],
      currentTimeSlotsList: [],
      communityId: "",
      serviceId: "",
      currentSelectedMouth: "", //当前选中日期对应的月份
      appointAheadDays: "", //可以提前预约的天数
      currentSlotId: undefined,
      currentStartTime: "",
      currentEndTime: "",
      currentDate: {},
      currentDateIndex: -1,
      currentTimeIndex: -1,
      lastDate: "", //确认预约单页面传过来的日期
      lastSlotId: -1, //确认预约单页面传过来的timeslotid
      optionalTimeSlotIndex: -1, //备选的slotId
    };
  },
  //mixins:[authorize],
  components: {},
  mounted() {},

  onLoad: function (options) {
    if (options) {
      this.communityId = options.communityId;
      this.serviceId = options.ServiceId;
      if (options.currentDate) {
        var newDate = options.currentDate.replaceAll("-", "/");
        this.lastDate = newDate;
        if (options.currentSlotId) {
          this.lastSlotId = options.currentSlotId;
        }
      }
    }
    this.getconfiginfo();
  },
  created() {},
  methods: {
    getEventChannel() {
      let pages = getCurrentPages();
      let currentPage = pages[pages.length - 1];
      return currentPage.getOpenerEventChannel();
    },
    getconfiginfo() {
      //获取店铺配置信息
      Taro.request({
        url: `${this.apiMobileUrl}/reservationtimeslot/getconfiginfo?communityId=${this.communityId}&ServiceId=${this.serviceId}`,
        data: {},
        header: {
          "content-type": "application/json", // 默认值
        },
        method: "GET",
        success: (res) => {
          if (res.data.isSuccess) {
            if (res.data.data) {
              this.dateList = res.data.data;
              let weeks = [
                "周日",
                "周一",
                "周二",
                "周三",
                "周四",
                "周五",
                "周六",
              ];
              this.appointAheadDays = this.dateList.length;
              this.dateList.forEach((element, index) => {
                var newDate = element.date.replaceAll("-", "/");
                element.date = newDate;
                if (this.lastDate) {
                  //如果确认预约单页面传过来的有日期，则选中这个日期
                  if (element.date == this.lastDate) {
                    element.isChecked = true;
                    this.currentDateIndex = index;
                    this.currentDate = element;
                    this.currentTimeSlotsList = element.timeSolts;
                    this.currentTimeSlotsList.forEach(
                      (timeElement, timeIndex) => {
                        if (
                          !timeElement.isFull &&
                          timeElement.isReservation &&
                          timeElement.surplus > 0
                        ) {
                          timeElement.isDisable = false;
                          if (timeElement.timeSlotId == this.lastSlotId) {
                            timeElement.isChecked = true;
                            this.currentSlotId = timeElement.timeSlotId;
                            this.currentStartTime = timeElement.startTime;
                            this.currentEndTime = timeElement.endTime;
                            this.currentTimeIndex = timeIndex;
                          } else {
                            if (!this.currentSlotId) {
                              console.log(
                                "this.optionalTimeSlotIndex:",
                                this.optionalTimeSlotIndex
                              );
                              this.optionalTimeSlotIndex = index;
                            }
                          }
                        } else {
                          timeElement.isDisable = true;
                          if (timeElement.isFull) {
                            timeElement.tip = "已约满";
                          } else if (!timeElement.isReservation) {
                            timeElement.tip = "不可预约";
                          }
                        }
                      }
                    );
                    if (
                      !this.currentSlotId &&
                      this.optionalTimeSlotIndex &&
                      this.optionalTimeSlotIndex != -1
                    ) {
                      this.currentTimeSlotsList[
                        this.optionalTimeSlotIndex
                      ].isChecked = true;
                      let element =
                        this.currentTimeSlotsList[this.optionalTimeSlotIndex];
                      this.currentSlotId = element.timeSlotId;
                      this.currentStartTime = element.startTime;
                      this.currentEndTime = element.endTime;
                      this.currentTimeIndex = optionalTimeSlotIndex;
                      this.optionalTimeSlotIndex = -1;
                      let list = JSON.parse(
                        JSON.stringify(this.currentTimeSlotsList)
                      );
                      this.currentTimeSlotsList = list;
                    }
                  } else {
                    element.isChecked = false;
                    element.timeSolts.forEach((timeElement, timeIndex) => {
                      if (
                        !timeElement.isFull &&
                        timeElement.isReservation &&
                        timeElement.surplus > 0
                      ) {
                        timeElement.isDisable = false;
                      } else {
                        timeElement.isDisable = true;
                        if (timeElement.isFull) {
                          timeElement.tip = "已约满";
                        } else if (!timeElement.isReservation) {
                          timeElement.tip = "不可预约";
                        }
                      }
                    });
                  }
                } else {
                  if (index === 0) {
                    element.isChecked = true;
                    this.currentTimeSlotsList = element.timeSolts;
                    this.currentTimeSlotsList.forEach(
                      (timeElement, timeIndex) => {
                        if (
                          !timeElement.isFull &&
                          timeElement.isReservation &&
                          timeElement.surplus > 0
                        ) {
                          //可预约的
                          timeElement.isDisable = false;
                          if (!this.currentSlotId) {
                            timeElement.isChecked = true;
                            this.currentSlotId = timeElement.timeSlotId;
                            this.currentStartTime = timeElement.startTime;
                            this.currentEndTime = timeElement.endTime;
                            this.currentTimeIndex = timeIndex;
                          }
                        } else {
                          timeElement.isDisable = true;
                          if (timeElement.isFull) {
                            timeElement.tip = "已约满";
                          } else if (!timeElement.isReservation) {
                            timeElement.tip = "不可预约";
                          }
                        }
                      }
                    );
                    this.currentDate = element;
                    this.currentDateIndex = 0;
                    var newCurrentDate = new Date(this.currentDate.date);
                    this.currentSelectedMouth = newCurrentDate.getMonth() + 1;
                  } else {
                    element.isChecked = false;
                    element.timeSolts.forEach((timeElement, timeIndex) => {
                      if (
                        !timeElement.isFull &&
                        timeElement.isReservation &&
                        timeElement.surplus > 0
                      ) {
                        //可预约的
                        timeElement.isDisable = false;
                      } else {
                        timeElement.isDisable = true;
                        if (timeElement.isFull) {
                          timeElement.tip = "已约满";
                        } else if (!timeElement.isReservation) {
                          timeElement.tip = "不可预约";
                        }
                      }
                    });
                  }
                }
                if (element.date) {
                  var newCurrentDate = new Date(element.date);
                  element.day = newCurrentDate.getDate();
                  element.weekday = weeks[newCurrentDate.getDay()];
                }
              });
              //如果数据遍历完，不存在之前选中的天，则选中当前天
              if (this.currentDateIndex == -1) {
                console.log("当前没有可以选中的天数");
                this.currentDate = this.dateList[0];
                this.dateList[0].isChecked = true;
                console.log("this.dateList[0]:", this.dateList[0]);
                this.currentTimeSlotsList = this.dateList[0].timeSolts;
                this.currentDateIndex = 0;
                var newCurrentDate = new Date(this.currentDate.date);
                this.currentSelectedMouth = newCurrentDate.getMonth() + 1;
                this.currentTimeSlotsList.forEach((timeElement, timeIndex) => {
                  if (
                    !timeElement.isFull &&
                    timeElement.isReservation &&
                    timeElement.surplus > 0
                  ) {
                    //可预约的
                    timeElement.isDisable = false;
                    if (!this.currentSlotId) {
                      timeElement.isChecked = true;
                      this.currentSlotId = timeElement.timeSlotId;
                      this.currentStartTime = timeElement.startTime;
                      this.currentEndTime = timeElement.endTime;
                      this.currentTimeIndex = timeIndex;
                    }
                  } else {
                    timeElement.isDisable = true;
                    if (timeElement.isFull) {
                      timeElement.tip = "已约满";
                    } else if (!timeElement.isReservation) {
                      timeElement.tip = "不可预约";
                    }
                  }
                });
              }
              console.log("this.dateList:", this.dateList);
            }
          } else {
            Taro.showToast({
              title: res.data.message,
              icon: "warn",
              duration: 2000,
            });
          }
        },
      });
    },

    selectDate(index) {
      //选择日期
      this.currentSlotId = undefined;
      if (this.dateList[index].date != this.currentDate.date) {
        this.dateList[this.currentDateIndex].isChecked = false;
        if (this.currentTimeIndex != -1) {
          this.dateList[this.currentDateIndex].timeSolts[
            this.currentTimeIndex
          ].isChecked = false;
        }
        this.dateList[index].isChecked = true;
        this.currentTimeSlotsList = this.dateList[index].timeSolts;
        this.currentTimeSlotsList.forEach((timeElement, timeIndex) => {
          if (
            !timeElement.isFull &&
            timeElement.isReservation &&
            timeElement.surplus > 0 &&
            !this.currentSlotId
          ) {
            timeElement.isChecked = true;
            this.currentSlotId = timeElement.timeSlotId;
            this.currentStartTime = timeElement.startTime;
            this.currentEndTime = timeElement.endTime;
            this.currentTimeIndex = timeIndex;
          }
        });
        this.currentDate = this.dateList[index];
        this.currentDateIndex = index;
        if (this.currentDate.date) {
          var currentDate = new Date(this.currentDate.date);
          this.currentSelectedMouth = currentDate.getMonth() + 1;
        }
      }
    },

    selectTimeSlot(index) {
      //选择时间
      if (this.currentTimeIndex != index) {
        if (!this.currentTimeSlotsList[index].isDisable) {
          this.currentTimeSlotsList[this.currentTimeIndex].isChecked = false;
          this.currentTimeSlotsList[index].isChecked = true;
          let list = [...this.currentTimeSlotsList];
          this.currentTimeSlotsList = JSON.parse(JSON.stringify(list));
          let timeSlotObj = this.currentTimeSlotsList[index];
          this.currentSlotId = timeSlotObj.timeSlotId;
          this.currentStartTime = timeSlotObj.startTime;
          this.currentEndTime = timeSlotObj.endTime;
          this.currentTimeIndex = index;
        } else {
          console.log("disable的不能点");
        }
      }
    },

    confirm() {
      let date = this.currentDate.date.replaceAll("/", "-");
      let startTime = this.currentStartTime;
      let endTime = this.currentEndTime;
      let timeSlotId = this.currentSlotId;
      console.log(
        "选中的日期：",
        date,
        ", 开始时间：",
        startTime,
        ", 结束时间：",
        endTime,
        ",timeSlotId:",
        timeSlotId
      );
      let myEventChannel = this.getEventChannel();
      Taro.navigateBack({
        success: function (res) {
          myEventChannel.emit("acceptDataFromTimePage", {
            reservationDate: date,
            timeSlotId: timeSlotId,
            startTime: startTime,
            endTime: endTime,
          });
        },
      });
    },
    //end
  },
};
</script>

